<template>
  <div class="city-container">
    <div class="message">
      <div>
        <button @click="changed('coke')">可乐罐</button>
        <button @click="changed('blenderroom')">blender卧室</button>
      </div>
    </div>
    <div id="container" ref="container"></div>
  </div>
</template>

<script>
import { InitThree } from "../../utils/init-three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";

import { DirectionalLight } from "three";

export default {
  name: "bed-room",
  data() {
    return {
      initThree: null,
      scene: null,
      draco: null,
      loader: null,
      dracoLoader: null,
      currentModel: null,
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.initThree = new InitThree(this.$refs.container);
      this.scene = this.initThree.scene;
      this.initThree.camera.position.set(10, 6, 1);
      this.addLight();
      this.loadingModel();
      this.animate();
    },

    addLight() {
      const directionalLight = new DirectionalLight(0xffffff, 0.5);
      directionalLight.position.set(10, 10, 10);
      this.scene.add(directionalLight);
      // const helper = new DirectionalLightHelper(directionalLight, 5);
      // this.scene.add(helper);
    },

    loadingModel(name = "coke") {
      if (!(this.loader & this.dracoLoader)) {
        this.loader = new GLTFLoader();
        this.dracoLoader = new DRACOLoader();
      }
      this.dracoLoader.setDecoderPath("model/gltf/draco/");
      this.loader.setDRACOLoader(this.dracoLoader);
      this.loader.load(
        `model/gltf/${name}.gltf`,
        (gltf) => {
          this.currentModel = gltf.scene;
          this.currentModel.name = name;
          this.scene.add(this.currentModel);
        },
        (xhr) => {
          console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
        },
        (error) => {
          console.log(error);
        }
      );
    },

    animate() {
      this.initThree.render();
      requestAnimationFrame(this.animate.bind(this));
    },
    changed(name) {
      this.currentModel.visible = false;
      const model = this.scene.getObjectByName(name);
      if (model) {
        this.currentModel = model;
        model.visible = true;
        return;
      }
      this.loadingModel(name);
    },
  },
  beforeDestroy() {
    this.initThree.destroy();
    this.dracoLoader.dispose();
    this.dracoLoader = null;
  },
};
</script>

<style lang="scss" scoped>
.city-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.message {
  height: 50px;
  width: 100%;
}
#container {
  flex: 1;
  width: 100%;
  background: #32373e;
}
button{
  margin-right:10px;
}
</style>
